from PyQt5.Qt import QThread
from PyQt5.QtWidgets import QWidget,QApplication
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5 import uic
from camera import Camera_Thread

import time, json, sys, logging, os

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

class Window(QWidget):
    gui_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.msg_history=list()
        self.hsv_value = ""
        self.setup_ui()
        self.bet = 0
        
    def setup_ui(self):
        self.ui = uic.loadUi("mainwindow.ui")
        # self.textBrowser_log = self.ui.textBrowser_log      # 日志显示区
        self.Label_camera = self.ui.label_camera            # 摄像头图片显示区

        self.tabWeight_2 = self.ui.tabWidget_2
        self.Button_X = self.ui.pushButton_3                # 关闭按钮
        self.Button_min = self.ui.pushButton

        
        self.ui.setWindowIcon(QIcon("./pic/ic.ico"))
        self.Button_min.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./pic/min.png);")
        self.Button_X.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./pic/close.png);")
        # self.label6 = self.ui.label_6                       # 设置标题图标
        # self.label6.setStyleSheet("background-color:rgb(19, 13, 81);\n""image:url(./pic/IOA8.png);")

        # 给按钮添加事件（即点击后要调用的函数）

        self.Button_X.clicked.connect(self.Button_X_clicked)
        self.tabWeight_2.currentChanged.connect(self.tabweight_change_camershow)
        self.gui_signal.connect(self.gui_signal_dispatch)

        self.camera = Camera_Thread(self.Label_camera, self.gui_signal)   # 建立摄像头线程
        self.camera.start()

    def tabweight_change_camershow(self):
        num = self.tabWeight_2.currentIndex()
        pass

    def move_QR(self,num):
        try:
            pass
 

        except Exception as e:
            logger.error(e,exc_info=True)

    # 切换程序
    def tabweight_change(self,):
        try:
            num =  self.tabWeight.currentIndex()
            pass

        except Exception as e:
            logger.error(e,exc_info=True)

    # 关闭所有进程
    def Button_X_clicked(self):
        pass

    # 复位
    def Button_reset_clicked(self):
        try:
            self.log("仓库已复位")
            self.camera.master.auto_flag = 0
            self.camera.master.action_flag = 0
            # self.camera.master.camera_position = 1
            self.move_QR(num=19)
            
        except Exception as e:
            self.log(f"复位失败，原因是{e}")       
    
    # 停止
    def Button_stop_clicked(self):
        try:
            self.log("停止已按下")
            self.camera.master.auto_flag = 0
            self.camera.master.action_flag = 0

        except Exception as e:
            self.log(f"停止失败，原因是{e}")

    # 自动运行
    def Button_Auto_clicked(self):
        try:
            self.ui.pushButton_2.setEnabled(False)
            self.ui.pushButton_4.setEnabled(False)
            self.ui.pushButton_5.setEnabled(False)
            self.ui.pushButton_6.setEnabled(False)
            self.ui.pushButton_7.setEnabled(False)
            self.ui.pushButton_8.setEnabled(False)
            self.ui.pushButton_9.setEnabled(False)
            self.ui.pushButton_10.setEnabled(False)
            self.ui.pushButton_11.setEnabled(False)

            self.ui.pushButton_12.setEnabled(False)
            self.ui.pushButton_13.setEnabled(False)

            self.camera.master.auto_flag = 1
            self.camera.master.auto_first = 1
            num =  self.tabWeight.currentIndex()
            pass

        except Exception as e:
            self.log(f"自动运行失败，原因是{e}")

    # 手动运行
    def Button_mumul_clicked(self):
        try:
            self.camera.master.auto_flag = 0
            self.camera.master.camera_position = 1
            self.move_QR(num=20)
            self.ui.pushButton_2.setEnabled(True)
            self.ui.pushButton_4.setEnabled(True)
            self.ui.pushButton_5.setEnabled(True)
            self.ui.pushButton_6.setEnabled(True)
            self.ui.pushButton_7.setEnabled(True)
            self.ui.pushButton_8.setEnabled(True)
            self.ui.pushButton_9.setEnabled(True)
            self.ui.pushButton_10.setEnabled(True)
            self.ui.pushButton_11.setEnabled(True)


            self.ui.pushButton_12.setEnabled(True)
            self.ui.pushButton_13.setEnabled(True)

            
        except Exception as e:
            self.log(f"手动运行失败，原因是{e}")

    # 信号调度
    def gui_signal_dispatch(self,msg):
        msg = json.loads(msg)
        source = int(msg.get("source"))   # 判断来自哪里的信号
        pass


    # 打印日志
    def log(self,msg):
        msg =time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+":  "+msg
        self.msg_history.append(msg)
        self.textBrowser_log.setText("<br>".join(self.msg_history))
        self.textBrowser_log.moveCursor(self.textBrowser_log.textCursor().End)
        self.textBrowser_log.repaint()  # 更新内容，如果不更新可能没有显示新内容

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.ui.show()
    app.exec()
